package com.zt.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zt.annotation.AdminLog;
import com.zt.common.Result;
import com.zt.service.AdminLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员操作日志控制器
 * @author 周明震
 * @date 2025/7/21
 */
@RestController
@RequestMapping("/admin/logs")
public class AdminLogController {
    
    @Autowired
    private AdminLogService adminLogService;
    
    /**
     * 分页查询操作日志
     */
    @PostMapping("/list")
    public Result getLogList(@RequestBody Map<String, Object> params) {
        try {
            int pageNum = (Integer) params.getOrDefault("pageNum", 1);
            int pageSize = (Integer) params.getOrDefault("pageSize", 10);

            // 处理空字符串参数，将空字符串设置为null
            if (params.get("startTime") != null && params.get("startTime").toString().trim().isEmpty()) {
                params.put("startTime", null);
            }
            if (params.get("endTime") != null && params.get("endTime").toString().trim().isEmpty()) {
                params.put("endTime", null);
            }
            if (params.get("adminUsername") != null && params.get("adminUsername").toString().trim().isEmpty()) {
                params.put("adminUsername", null);
            }
            if (params.get("module") != null && params.get("module").toString().trim().isEmpty()) {
                params.put("module", null);
            }
            if (params.get("operation") != null && params.get("operation").toString().trim().isEmpty()) {
                params.put("operation", null);
            }
            if (params.get("keyword") != null && params.get("keyword").toString().trim().isEmpty()) {
                params.put("keyword", null);
            }

            IPage<com.zt.entity.AdminLog> page = adminLogService.getLogPage(pageNum, pageSize, params);

            Map<String, Object> result = new HashMap<>();
            result.put("list", page.getRecords());
            result.put("total", page.getTotal());
            result.put("pageNum", page.getCurrent());
            result.put("pageSize", page.getSize());
            result.put("pages", page.getPages());

            return Result.success("查询成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取日志统计信息
     */
    @GetMapping("/stats")
    public Result getLogStats(@RequestParam(required = false) String startTime,
                             @RequestParam(required = false) String endTime) {
        try {
            LocalDateTime start = null;
            LocalDateTime end = null;
            
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            
            if (startTime != null && !startTime.isEmpty()) {
                start = LocalDateTime.parse(startTime, formatter);
            }
            if (endTime != null && !endTime.isEmpty()) {
                end = LocalDateTime.parse(endTime, formatter);
            }
            
            Map<String, Object> stats = adminLogService.getLogStats(start, end);
            return Result.success("获取成功", stats);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取统计信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 清理过期日志
     */
    @DeleteMapping("/clean")
    @AdminLog(module = "日志管理", operation = "清理", description = "清理过期日志", type = AdminLog.OperationType.DELETE)
    public Result cleanExpiredLogs(@RequestParam(defaultValue = "30") int days) {
        try {
            int count = adminLogService.cleanExpiredLogs(days);
            return Result.success("清理成功，共清理 " + count + " 条日志");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("清理失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出日志
     */
    @GetMapping("/export")
    public Result exportLogs(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        try {
            // 处理空字符串参数，将空字符串设置为null
            if (params.get("startTime") != null && params.get("startTime").toString().trim().isEmpty()) {
                params.put("startTime", null);
            }
            if (params.get("endTime") != null && params.get("endTime").toString().trim().isEmpty()) {
                params.put("endTime", null);
            }
            if (params.get("adminUsername") != null && params.get("adminUsername").toString().trim().isEmpty()) {
                params.put("adminUsername", null);
            }
            if (params.get("module") != null && params.get("module").toString().trim().isEmpty()) {
                params.put("module", null);
            }
            if (params.get("operation") != null && params.get("operation").toString().trim().isEmpty()) {
                params.put("operation", null);
            }
            if (params.get("keyword") != null && params.get("keyword").toString().trim().isEmpty()) {
                params.put("keyword", null);
            }

            List<com.zt.entity.AdminLog> logs = adminLogService.exportLogs(params);
            
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String fileName = "admin_logs_" + System.currentTimeMillis() + ".csv";
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            
            // 生成CSV内容
            StringBuilder csv = new StringBuilder();
            csv.append("ID,管理员ID,管理员用户名,操作模块,操作类型,操作描述,请求方法,请求URL,操作状态,客户端IP,执行时间(ms),创建时间\n");
            
            for (com.zt.entity.AdminLog log : logs) {
                csv.append(log.getId()).append(",")
                   .append(log.getAdminId()).append(",")
                   .append(log.getAdminUsername()).append(",")
                   .append(log.getModule()).append(",")
                   .append(log.getOperation()).append(",")
                   .append("\"").append(log.getDescription()).append("\"").append(",")
                   .append(log.getMethod()).append(",")
                   .append(log.getUrl()).append(",")
                   .append(log.getStatus() == 1 ? "成功" : "失败").append(",")
                   .append(log.getIp()).append(",")
                   .append(log.getExecuteTime()).append(",")
                   .append(log.getCreatedAt()).append("\n");
            }
            
            response.getWriter().write(csv.toString());
            response.getWriter().flush();
            
            return null; // 文件下载不需要返回Result
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导出失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取日志详情
     */
    @GetMapping("/{id}")
    public Result getLogDetail(@PathVariable Long id) {
        try {
            com.zt.entity.AdminLog log = adminLogService.getById(id);
            if (log == null) {
                return Result.error("日志不存在");
            }
            return Result.success("获取成功", log);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取日志详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除日志
     */
    @DeleteMapping("/batch")
    @AdminLog(module = "日志管理", operation = "删除", description = "批量删除日志", type = AdminLog.OperationType.DELETE)
    public Result batchDeleteLogs(@RequestBody List<Long> ids) {
        try {
            boolean result = adminLogService.removeByIds(ids);
            if (result) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 清空所有日志（临时方法，用于测试）
     */
    @DeleteMapping("/clear-all")
    @AdminLog(module = "日志管理", operation = "清空", description = "清空所有日志", type = AdminLog.OperationType.DELETE)
    public Result clearAllLogs() {
        try {
            adminLogService.clearAllLogs();
            return Result.success("清空成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("清空失败：" + e.getMessage());
        }
    }
}
